<?php

/**
 * @Author: king
 * @Date:   2019-05-05 19:58:37
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-04 14:31:29
 */

namespace App\Http\Controllers\Api\v1\Order;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use App\Models\Api\Rectification as RectificationModel;
use App\Http\Controllers\Api\v1\Pay\NotifyController;
use Illuminate\Http\Request;
use DB;
/**
 * 苹果支付结果验证
 * Class AppPayVerify
 * @doc https://developer.apple.com/library/archive/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104-SW4
 * @package
 */
class AppPayVerifyController extends BaseController
{

    public function index(Request $request)
    {
        $param = $request->only(['ticket', 'order_id']);

        $ticket['receipt-data'] = $param['ticket'];
         \Log::info('苹果支付：' . var_export($ticket,true));
//        $ticket['receipt-data'] = 'MIIT0wYJKoZIhvcNAQcCoIITxDCCE8ACAQExCzAJBgUrDgMCGgUAMIIDdAYJKoZIhvcNAQcBoIIDZQSCA2ExggNdMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATEwCwIBCwIBAQQDAgEAMAsCAQ8CAQEEAwIBADALAgEQAgEBBAMCAQAwCwIBGQIBAQQDAgEDMAwCAQoCAQEEBBYCNCswDAIBDgIBAQQEAgIAvTANAgENAgEBBAUCAwHViDANAgETAgEBBAUMAzEuMDAOAgEJAgEBBAYCBFAyNTIwGAIBAgIBAQQQDA5jb20ubGl1aGUueHpuczAYAgEEAgECBBDFJmEC90LcbWxkjnRnLBxpMBsCAQACAQEEEwwRUHJvZHVjdGlvblNhbmRib3gwHAIBBQIBAQQUc8JDTxznbG0mXo2dih6zMs2DawowHgIBDAIBAQQWFhQyMDE5LTA1LTMxVDAyOjM4OjQzWjAeAgESAgEBBBYWFDIwMTMtMDgtMDFUMDc6MDA6MDBaMEUCAQcCAQEEPboho+0Ad5d27Qkyp0NaJMwkRd47k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FmnBQl8F0BWER5007eLIztHo9VvJOLr0bdw3w9F4SfK8W147ee1Fxeo3H4iNcol1dkP1mvUoiQjEfehrI9zgWDGG1sJL5Ky+ERI8GA4nhX1PSZnIIozavcNgs/e66Mv+VNqW2TAYzN39zoHLFbr2g8hDtq6cxlPtdk2f8GHVdmnmbkyQvvY1XGefqFStxu9k0IkEirHDx22TZxeY8hLgBdQqorV2uT80AkHN7B1dSExggHLMIIBxwIBATCBozCBljELMAkGA1UEBhMCVVMxEzARBgNVBAoMCkFwcGxlIEluYy4xLDAqBgNVBAsMI0FwcGxlIFdvcmxkd2lkZSBEZXZlbG9wZXIgUmVsYXRpb25zMUQwQgYDVQQDDDtBcHBsZSBXb3JsZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9ucyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQIIDutXh+eeCY0wCQYFKw4DAhoFADANBgkqhkiG9w0BAQEFAASCAQCgoW8NZa6CoBdvzT7LVRhRDf8HCIVwdzZzQ+/tXN0HgMx7HYCINIPvJOjh+orZaNCyB06OjzVUMvPE4xK0LDbt265iPJI9MmJgPnYGL8/HsmBUGWVKaf6bmnEeOeKk7GEObT07gllA4CQpa8Zifo+37KsZ06MK/I6YFFl1pwWCpBy9JSKkniV1PRW+aCB7F5EwgZ93mRGEpP0obOUDzD6BE+oqRGqiefT6yUnRABJrjV3a6AyIkNBP3/bQb8BmFxjElfbdUrA5a018O6fQdYZLjTLnOHVGMDC/tKIf762irlO0e/vXsFFwqQePlTAepZ66p+JRG4jBMTOXIHOpAQnC';
        $res = curl(config('apple_pay_goods.notify_ur'),1,json_encode($ticket, true));
        $res = json_decode($res, true);
        $uid = $request->uid;

        if (isset($res['status']) && $res['status'] == 0)
        {
            $rid = [];
            $status = 3;
            $OrdersModel = new Orders();
            $num = substr($param['order_id'], 1, 1);
            $orders = $OrdersModel->get_orders_detail(['uid'=>$uid,'order_ids' => [0 => $param['order_id']], 'order_type' => $num]);

            $startTransStatus = true;
            DB::beginTransaction();
            try
            {
                // 修改生时校正状态
                if ($num == 1 && (int)$orders[0]['reid'] > 0)
                {
                   (new RectificationModel())->where(['id' => (int)$orders[0]['reid']])->update(['status' => 1]);// 支付完成，等待校正
                }
                // 修改订单状态
                $OrdersModel->where(['order_id' => $param['order_id']])->update(['status' => 1, 'pay_time' => time()]);// 支付成功

                DB::commit();
            }
            catch (\Exception $e)
            {
                $startTransStatus = false;
                DB::rollback();
            }

             $OrdersModel->rm_cache(['type' => 4, 'order_id' => $param['order_id'], 'uid' => $uid], $rid);

            // 付款成功  开始生时校正
            if ($startTransStatus === true && $num == 1 && (int)$orders[0]['reid'] > 0)
            {
                try
                {
                $rectification = (new RectificationModel())->where(['id' => (int)$orders[0]['reid']])->first();
                $event_array   = $rectification->events()->get()->toArray();
                $recode        = (new Recode())->where(['id' => $rectification['rid']])->first();
                }
                catch (\Exception $e)
                {
                    \Log::info('ali支付回调，获取生时矫正相关信息失败：' . $e->getMessage());

                    $rectification = [];
                    $recode = [];
                    $event_array = [];
                }

                 $rid = $rectification;
                 $status = 2;

                if ($rectification && $event_array && $recode)
                {
                    $jobData = [
                        'oid' => $orders[0]['oid'],
                        'order_id' => $param['order_id'],
                        'reid' => $orders[0]['reid'],
                        'start_time' => $rectification['start_time'],
                        'end_time' => $rectification['end_time'],
                        'events' => $event_array,
                        'recode' => $recode
                    ];
                    $queueConfig = config('queue');
                    queuePush($queueConfig['rectification_task'], $jobData, $queueConfig['rectification_queue'], $queueConfig['rectification_delay']);
                }
            }

            // 付款成功  开始添加运势计算
            if ($startTransStatus === true && $num == 2 && (int)$orders[0]['fid'] > 0)
            {
                try
                {
                    $fortune_type = (new NotifyController())->push_fortune(['uid' => $uid, 'oid' => $orders[0]['oid']]);
                }
                catch (\Exception $e)
                {
                    $fortune_type = 0;
                    \Log::info('ali支付回调，运势加入队列失败：' . $e->getMessage());
                }
             $rid = $fortune_type;
             $status = 2;
            } else
            {
                $fortune_type = 0;
            }

            if ($startTransStatus === true)
            {
                //订单支付数量增加
                $OrdersModel->inc_order_num(['order_type' => $num, 'fortune_type' => $fortune_type]);
            }
             // 删除订单缓存
            $OrdersModel->rm_cache(['type' => 4,'oid' => $orders[0]['oid'], 'del_add' => 0, 'order_id' => $param['order_id'], 'uid' => $uid,'status' => $status],$rid);

            return show(config('code.success'), '请求成功');
        } else
        {
            return show(config('code.error'), '请求失败');
        }
    }
}
